package test.orm;


import java.util.List;

import org.apache.ibatis.session.SqlSession;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import zdy.web.bean.User;
import zdy.web.orm.mybatis1.UserDao;
import zdy.web.orm.mybatis1.mybatisFactory;



public class temybatis1 {
	SqlSession sqlSession;
	UserDao userDao ;
	@Before
	public void setUp() throws Exception {
		///这种做法是错误的 ，因为sqlSession 不是线程安全的
		 sqlSession = mybatisFactory.getSqlSession();
		 userDao = sqlSession.getMapper(UserDao.class);
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void selectByID() {
	
		int id = 1;
		User curUser = userDao.selectByID(id);
		if (curUser != null) {
			System.out.println("selectByID:" + curUser.getName());
		}
	}

	@Test
	public void selectsByName() {
	
		String name = "x";
		List<User> users = userDao.selectsByName(name);
		if (!users.isEmpty()) {
			System.out.println("selectsByName begin:");
			for (User u : users) {
				System.out.println(u.getName());
			}
			System.out.println("selectsByName end:");
		}
	}

	//@Test
    public void addUser() {
        User user = new User();
        user.setAddress("place");
        user.setName("test_add");
        user.setAge(30);
        
     
        try {
        	
        	userDao.insert(user);
        	sqlSession.commit();
            System.out.println("新增用户ID：" + user.getId());
        } finally {
        	sqlSession.close();
        }
    }

    /**
     * 修改后要commit
     */
	//@Test
    public void updateUser() {
    
         try {
         
            User user = userDao.selectByID(1);
            if (user != null) {
                user.setAddress("A new place");
                userDao.update(user);
                sqlSession.commit();
                System.out.println("修改用户，ID=" + user.getId());
            }
        } finally {
        	sqlSession.close();
        }
    }

    /**
     * 删除后要commit.
     * 
     * @param id
     */
	//@Test
    public void deleteUser(int id) {
    
         try {
         
         	userDao.delete(id);
         	sqlSession.commit();
            System.out.println("删除用户，ID=" + id);
        } finally {
        	sqlSession.close();
        }
    }
}
